# application/services/detection/mistake.py
from application.mapper.detection.mistake import MistakeMapper
from typing import Dict, Any, List, Tuple
from application.models.detection.mistake import Mistake
from application.utils.res import models_to_dicts_camel, to_snake_case


class MistakeService:
    """错误服务层"""

    @staticmethod
    def get_mistake_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> Tuple[List[Dict[str, Any]], int]:
        """
        分页获取错误数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (错误数据列表, 总数)
        """
        mistake_list, total = MistakeMapper.get_mistake_list(
            page_num, page_size, conditions
        )

        result_list = models_to_dicts_camel(mistake_list)

        return result_list, total
    @staticmethod
    def create_mistake(mistake_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建错误记录
        :param mistake_data: 错误数据
        :return: 创建后的错误数据
        """
        # 创建错误对象
        mistake = Mistake()

        for key, value in mistake_data.items():
            snake_key = to_snake_case(key)
            if hasattr(mistake, snake_key):
                setattr(mistake, snake_key, value)
        
        created_mistake = MistakeMapper.create_mistake(mistake)
        return models_to_dicts_camel([created_mistake])[0]

    @staticmethod
    def update_mistake(mistake_id: int, mistake_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新错误记录
        :param mistake_id: 错误ID
        :param mistake_data: 错误数据
        :return: 更新后的错误数据
        """
        mistake = MistakeMapper.get_mistake_by_id(mistake_id)
        
        if not mistake:
            return None
            
        # 更新错误对象
        for key, value in mistake_data.items():
            snake_key = to_snake_case(key)
            if hasattr(mistake, snake_key):
                setattr(mistake, snake_key, value)
        
        updated_mistake = MistakeMapper.update_mistake(mistake)
        return models_to_dicts_camel([updated_mistake])[0]

    @staticmethod
    def batch_delete_mistake(mistake_ids: list) -> bool:
        """
        批量删除绕组
        :param coil_ids: 绕组ID列表
        :return: 删除的记录数
        """
        deleted_count = MistakeMapper.batch_delete_mistake(mistake_ids)
        return deleted_count